package com.niuwa.p2p.service.role.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.mvc.entity.JsonResult;
import com.niuwa.p2p.core.utils.AppConstants;
import com.niuwa.p2p.dao.role.RoleResourceDao;
import com.niuwa.p2p.entity.role.RoleResource;
import com.niuwa.p2p.service.role.RoleResourceService;

@Service
public class RoleResourceServiceImpl implements RoleResourceService{
	
	@Autowired
	private RoleResourceDao roleResourceDao;

	@Override
	public JsonResult saveRoleResource(RoleResource roleResource) {
		JsonResult jsonResult=new JsonResult(false,"资源绑定失败!");
		if (null!=roleResource) {
			String roleIds=roleResource.getRoleIds();
			List<String> resourceIds=roleResource.getResourceIds();
			int obj = 0,tag =0;
			if (StringUtils.isNotBlank(roleIds) && !resourceIds.isEmpty()) {
				resourceIds.remove(AppConstants.ROLE_ROOT_ID);//移除根节点
				String[] roleIdArry=roleResource.getRoleIds().split(",");
				tag=(roleIdArry.length)*(roleResource.getResourceIds().size());
				//先清空角色、资源
				deleteRoleResource(roleIdArry);
				for (String roleId : roleIdArry) {
					for (String resourceId : roleResource.getResourceIds()) {
						obj+=roleResourceDao.saveRoleResource(Integer.parseInt(roleId),
								Integer.parseInt(resourceId));//影响行数
					}
				}
			}
			if (obj==tag) {
				jsonResult.setSuccess(true);
				jsonResult.setMsg("资源绑定成功!");
			}
		}
		return jsonResult;
	}

	@Override
	public JsonResult deleteRoleResource(String[] roleIdArry) {
		JsonResult jsonResult=new JsonResult(false,"资源解绑失败!");
		int obj = 0;
		int	tag =roleIdArry.length;
		for (String roleId : roleIdArry) {
			obj+=roleResourceDao.deleteRoleResource(Integer.parseInt(roleId));//影响行数
		}
		if (obj==tag) {
			jsonResult.setSuccess(true);
			jsonResult.setMsg("资源解绑成功!");
		}
		return jsonResult;
	}

}
